package com.heepay;

import com.heepay.common.HttpUtil;
import com.heepay.common.MyKey;
import com.heepay.common.SignEncrypt;
import org.bouncycastle.util.encoders.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

/**
 *
 * 该接口为快捷发送支付短信接口，需要获取到响应然后解密
 * 拿到hy_token_id去调确认支付
 *
 */

public class SendPaySMS {
    public static void main(String[] args) throws Exception {
        Date now = new Date();
        // 创建 SimpleDateFormat 对象，指定日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = dateFormat.format(now);

        //商户编号，（汇付宝商户内码：七位整数数字）
        String agent_id = "1664502";

        //二级商户号，传了要参与签名（集团商户模式）
        String ref_agent_id = "";
        //是否分润单，传了要参与签名（集团商户模式；分润单需要调分润接口，不然不会结算）
        String is_guarantee = "1";

        //版本号，固定为1
        String version = "1";
        //商户订单号
        String agent_bill_id = timestamp;
        //商户订单时间，格式为"yyyyMMddhhmmss"
        String agent_bill_time = timestamp;
        //支付金额，单位：元，保留二位小数
        String pay_amt = "0.01";
        //商品名称，中文UTF-8处理
        String goods_name = "手机";
        //授权码
        String hy_auth_uid = "";
        //用户IP地址
        String user_ip = "127.168.0.1";
        //支付后返回的商户处理页面，URL参数是以http://或https://开头的完整URL地址(后台处理)，提交的url地址必须外网能访问到，否则无法通知商户。值可以为空，但不可以为null。
        String notify_url = "https://pay.heepay.com/test";

        //拼接待加密签名参数

        String signStr = "agent_bill_id=" + agent_bill_id +
                        "&agent_bill_time=" + agent_bill_time +
                        "&agent_id=" + agent_id +
                        "&goods_name=" + goods_name +
                        "&hy_auth_uid=" + hy_auth_uid +
                        "&is_guarantee=" +is_guarantee +
                        "&notify_url=" + notify_url +
                        "&pay_amt=" + pay_amt +
                        "&ref_agent_id=" + ref_agent_id +
                        "&user_ip=" + user_ip +
                        "&version=" + version;

        System.out.println("待加密签名串：--------->" + signStr);

        SignEncrypt signEncrypt = new SignEncrypt();
        // 使用类名和常量名来访问常量
        String publicKeystr = MyKey.publicKeystr;
        String privateKeystr = MyKey.privateKeystr;
        //密钥配置
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] publicKeyPath = Base64.decode(publicKeystr.getBytes());
        byte[] privateKeyPath = Base64.decode(privateKeystr.getBytes());
        PublicKey heepayPublicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyPath));
        PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyPath));
        //加密
        String content = signEncrypt.encrypt(signStr, heepayPublicKey);
        //加签
        String sign = signEncrypt.sign(signStr, privateKey);

        Map<String, String> map = new HashMap<>();
        map.put("encrypt_data", content);
        map.put("agent_id",agent_id);
        map.put("sign",sign);

        System.out.println("请求参数：--------->" + map);

        String Result = HttpUtil.sendPost("Https://Pay.Heepay.com/WithholdAuthPay/SendPaySMS.aspx",map);
        System.out.println("响应参数：--------->" + Result);

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            InputSource inputSource = new InputSource(new StringReader(Result));
            Document document = builder.parse(inputSource);

            // 提取节点的值
            String retMsg = getElementValue(document, "ret_msg");
            String encryptData = getElementValue(document, "encrypt_data");

            if ("已经发送短信验证码".equals(retMsg)){
                String a = signEncrypt.decrypt(encryptData,privateKey);
                String[] pairs = a.split("&");
                for (String pair : pairs ){
                    String[] keyValue = pair.split("=");
                    if (keyValue.length == 2 && "hy_token_id".equals(keyValue[0])) {
                        String hy_token_id = keyValue[1];
                        //hy_token_id为支付订单创建成功的标记，确定支付需要用上
                        System.out.println("hy_token_id的值: " + hy_token_id);
                        break;  // 如果找到目标键，可以提前结束循环
                    }else {
                        // 处理未成功分割的情况
                        System.out.println("无效的键值对: " + pair);
                    }
                }
            }else {
                System.out.println("错误信息：--------->"+retMsg);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    private static String getElementValue(Document document, String tagName) {
        NodeList nodeList = document.getElementsByTagName(tagName);
        if (nodeList.getLength() > 0) {
            Element element = (Element) nodeList.item(0);
            return element.getTextContent();
        }
        return null;
    }
}
